package com.gdut.msmservice.controller;

import com.gdut.commonutils.R;
import com.gdut.msmservice.service.MsmService;
import com.gdut.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author Drifiter
 * @create 2021-08-29 15:35
 */
@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
public class MsmController {


    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

//    发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){

        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }


        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        HashMap<String, Object> params = new HashMap<>();
        params.put("code",code);
        boolean isSend = msmService.send(params,phone);
        if (isSend){
            //发送成功，把发送成功验证码放到redis里面、
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }

    }


}
